<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">
                <el-row>
                    <el-form-item>
                        <el-text style="font-size: 20px;font-weight: bold;">{{examName}}考试监考</el-text>
                        <el-text style="color:red;">(10秒刷新一次页面)</el-text>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="需参考人数:" class="content">
                        <el-text>{{countStatus.examUserNum}}人</el-text>
                    </el-form-item>
                    <el-form-item label="在线人数:" class="content">
                        <el-text>{{countStatus.onlineNum}}人</el-text>
                    </el-form-item>
                    <el-form-item label="数据异常人员:" class="content">
                        <el-text>{{countStatus.dangerNum}}人</el-text>
                    </el-form-item>
                    <el-form-item label="离线人数:" class="content">
                        <el-text>{{countStatus.offlineNum}}人</el-text>
                    </el-form-item>
                    <el-form-item label="考前人脸验证失败人数:" class="content">
                        <el-text>{{countStatus.warnNum}}人</el-text>
                    </el-form-item>
                </el-row>
               <div style="overflow-y:scroll;overflow-x:hidden;height:100%;margin-left: 30px">
                   <el-checkbox-group v-model="checkList">
                       <div class="box" v-for="person in onlineStatusList" :key="person.id">
                           <el-checkbox :label="person.userId" :value="person.userId"  style="margin-right: 10px"><br/></el-checkbox>
                           <el-badge :value="person.status" class="item" :type="person.type">
                               <el-avatar shape="square"  :size="80" :src="imageSrc" @click="openDrawer(person.userId,route.query.examId)"/>
                           </el-badge>
                           <el-row style="margin-top: 20px">
                               <el-text>{{person.userName}}</el-text>
                           </el-row>
                       </div>
                   </el-checkbox-group>
               </div>
              <div style="margin-left: 50px">
                      <el-button type="warning" @click="examQualification">取消考试资格</el-button>
                      <el-button type="danger" @click="centerDialogVisible=true">取消本场考试</el-button>
              </div>
<!--  侧抽屉 行为记录      -->
            <el-drawer v-model="drawer" title="行为记录" :with-header="false" size="22%">
               <div class="drawer">
                   <span >行为记录</span>
               </div>
                <ul>
                    <li v-for="record in recordsList" :key="record.id" :class="getClass(record.statusFlag)">
                        {{ record.exceptionTime }}
                        <div v-if="record.statusFlag==2" style="margin-top: 20px">
                           <el-row style="margin-left: -20px">
                               <el-col :span="12" style="margin-left: -20px">
                                   <el-row class="center">
                                       <el-image :src="imgUrl" style="width: 100%" @click="showImgViewer"></el-image>
                                       <el-image-viewer v-if="imgViewerVisible"  :url-list="[imgUrl]" @close="closeImgViewer"/>
                                   </el-row>
                                  <el-row class="center">
                                      <span>参考人员原照</span>
                                  </el-row>
                               </el-col>
                               <el-col :span="12">
                                   <el-row class="center">
                                       <el-image :src="officeUrl+record.snapPhoto" style="width: 100%" @click="showImgViewer1(record.snapPhoto)"></el-image>
                                       <el-image-viewer v-if="imgViewerVisible1"  :url-list="[imgUrl1]" @close="closeImgViewer1"/>
                                   </el-row>
                                   <el-row class="center">
                                       <span>抓拍照片</span>
                                   </el-row>
                               </el-col>
                           </el-row>
                        </div>
                    </li>
                </ul>
                <div class="center">
                    <el-button type="warning" @click="sendWarning">发送警告</el-button>
                </div>
            </el-drawer>
        </div>
        <!-- 取消考试  -->
        <el-dialog v-model="centerDialogVisible"  width="20%">
            <el-row style="margin-bottom: 10px">
                <el-text style="color: red;font-weight: bold;font-size: 18px">请谨慎操作</el-text>
            </el-row>
            <el-row>
                <el-text style="font-weight: bold">本操作将彻底取消考试和禁止补考！</el-text>
            </el-row>
            <template #footer>
                      <span class="dialog-footer">
                        <el-button type="primary" style="margin-left: -10px;margin-top: -10px" @click="examCancel">确认</el-button>
                      </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="invigilation">
    import { useDict } from '/@/hooks/dict';
    import { useMessage } from "/@/hooks/message";
    import {getOnlineUser,getCountStatus,getRecords,closeBatchUser,cancelExam,sendWarn,personPic,getPic} from '/@/api/train/invigilation'
    import {office} from "/@/api/train/kszlFile";
    import { rule } from '/@/utils/validate';
    import {reactive, ref} from "vue";
    import {ElMessage} from "element-plus";
    import {useRouter} from "vue-router";
    import {Session} from "/@/utils/storage";
    import request from "/@/utils/request";
    import imageSrc from "/@/assets/tx.png"

    // 引入组件
    const route = useRoute();
    const timer = ref<number | null>(null);
    const timer1 = ref<number | null>(null);
    const emit = defineEmits<{ (event: 'update:modelValue', value: boolean): void; }>();
    // 定义变量内容
    const router = useRouter();
    const dataFormRef = ref();
    const officeUrl = ref()
    const form = ref();
    const m = ref((e) => { e.preventDefault(); }); // 初始化 m 为一个函数
    const m1 = ref((e) => { e.preventDefault(); }); // 初始化 m 为一个函数
    const onlineStatusList = ref([]);
    const drawer = ref(false)
    const visible = ref(false)
    const centerDialogVisible = ref(false)
    const imgViewerVisible = ref(false)
    const imgViewerVisible1 = ref(false)
    const loading = ref(false)
    // 定义校验规则
    const dataRules = ref({})
    const checkList = ref([])
    // 定义变量内容
    const warnId = ref()
    const formDialogRef = ref()
    const countStatus = reactive({})
    const recordsList = reactive([{}])
    const examName = ref()
    const baseUrl = ref()
    const imgUrl = ref()
    const imgUrl1 = ref()
    const record = ref({})

//挂载完毕
    onMounted( ()=> {
            // 初始调用fetchOnlineUser
           fetchOnlineUser();
            // 设置定时器，每10秒调用一次fetchOnlineUser
            timer.value = setInterval(fetchOnlineUser, 10000);
             office().then((res) => {
                officeUrl.value = res.data + '/downloadFile/';
                // console.log('officeUrl.value',officeUrl.value)
            });
            examName.value = route.query.examName;
             personPic().then((res) => {
                baseUrl.value = '/' + res.data;
            });
    });
// 调用getOnlineUser和getCountStatus接口的函数
    const fetchOnlineUser =  () => {
            const obj = {
                examId: route.query.examId
            }
            getOnlineUser(obj).then((res=>{
                onlineStatusList.value = res.data.map(item => {
                    const [status, type] = item.onlineStatus.split(',');
                    return {
                        ...item,
                        status: status.trim(),
                        type: type.trim(),
                    };
                });
            }));
            getCountStatus(obj).then((res=>{
                Object.assign(countStatus, res.data);
            }))
    };
    const showImgViewer = () => {
        imgViewerVisible.value = true;
        document.body.style.overflow = 'hidden';
        document.addEventListener('touchmove', m.value, { passive: false }); // 使用对象形式添加监听器，并设置 passive 为 false
    };
    const closeImgViewer = () => {
        imgViewerVisible.value = false;
        document.body.style.overflow = 'auto';
        document.removeEventListener('touchmove', m.value, { passive: false }); // 确保移除监听器时使用相同的选项
    };
    const showImgViewer1 = (val) => {
        imgUrl1.value = officeUrl.value+val
        imgViewerVisible1.value = true;
        document.body.style.overflow = 'hidden';
        document.addEventListener('touchmove', m1.value, { passive: false });
    };
    const closeImgViewer1 = () => {
        imgViewerVisible1.value = false;
        document.body.style.overflow = 'auto';
        document.removeEventListener('touchmove', m1.value, { passive: false });
    };
//行为记录
    const openDrawer = (userId:string,examId:string)=>{
        drawer.value = true
        record.value = {
            userId:userId,
            examId:examId
        }
        recordsList.length = 0
        warnId.value = userId
        getContent()
        timer1.value = setInterval(getContent, 10000);
    }
    const getContent = ()=>{
        getRecords( record.value).then((res=>{
            Object.assign(recordsList,res)
            recordsList.forEach(item=>{
                if(item.statusFlag==2){
                    let url = `${baseUrl.value}?username=${warnId.value}`
                    getPic(url).then(((res)=>{
                        try {
                            // 创建一个 Blob URL 来访问这个 Blob
                            const blobUrl = URL.createObjectURL(res);
                            // 使用 FileReader 将 Blob 转换为 Base64
                            const reader = new FileReader();
                            reader.readAsDataURL(res);
                            reader.onload = () => {
                                // 当读取完成时，将结果赋值给响应式引用
                                let imgUrlTmp = reader.result as string;
                                // console.log('imgUrlTmp',imgUrlTmp)
                                imgUrl.value = 'data:image/jpg;'+imgUrlTmp.substring(14);
                                // console.log('imgUrl.value',imgUrl.value)
                                // 释放 Blob URL
                                URL.revokeObjectURL(blobUrl);
                            };
                            reader.onerror = (error) => {
                                console.error('读取文件时出错:', error);
                            };
                        } catch (error) {
                            console.error('获取文件流时出错:', error);
                        }
                    }))
                }
            })
        }))
    }
    const  getClass = (statusFlag: number)=> {
        switch (statusFlag) {
            case 0:
                return 'normal-class';
            case 1:
                return 'abnormal-class';
            case 2:
                return 'substitution-class';
            case 3:
                return 'substitution1-class';
        }
    }
//取消考试资格
    const examQualification = ()=>{
        const obj = {
            examId: route.query.examId,
            userList:checkList.value
        }
        closeBatchUser(obj).then((res=>{
            ElMessage({
                message: '操作成功',
                type: 'success',
            })
            //取消考试资格人员离线
            onlineStatusList.value.forEach(item =>{
                for (let i = 0; i < checkList.value.length; i++) {
                    if (item.userId == checkList.value[i]) {
                        item.status = 'off'
                        item.type = 'info'
                    }
                }
            })
            checkList.value.length = 0
        })).catch(error=>{
            alert('失败');
        })
    }
//取消本场考试
    const examCancel=()=>{
        let obj = {
            examId:route.query.examId
        }
        cancelExam(obj).then((res=>{
            ElMessage({
                message: '操作成功',
                type: 'success',
            })
            //全员离线
            onlineStatusList.value.forEach(item => {
                item.status = 'off'
                item.type = 'info'
            });
            centerDialogVisible.value = false
        })).catch(error=>{
            alert('失败');
        })
    }
//发送警告
    const sendWarning=()=>{
        let obj = {
            userId: warnId.value,
            examId:route.query.examId
        }
        sendWarn(obj).then((res=>{
            ElMessage({
                message: '发送成功',
                type: 'success',
            })
        })).catch(error=>{
            alert('失败');
        })
}
// 确保组件卸载时清除定时器
    onUnmounted(() => {
        clearInterval(timer.value);
        clearInterval(timer1.value);
    });
</script>
<style lang="scss" scoped>
    .box{
        margin: 20px 20px 20px 0
    }
    .el-row{
        margin-left: 50px;
    }
    .content{
        margin-left: 20px;
        width: 260px;
        font-weight: bold;
    }
    .el-checkbox-group{
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        gap: 20px;
    }
    .drawer{
        font-size: 26px;
        font-weight: bold;
        text-align: center;
        letter-spacing: 8px;
    }
    .el-checkbox__label {
        display: none !important;
    }
    .center{
        display: flex;
        justify-content: center;
        font-size: 12px;
    }
    li{
        margin: 20px;
    }
    .normal-class::before {
        content: '开始考试  ●';
        color: #0A74F6; /* 正常考试显示蓝色 */
        margin-right: 20px; /* 小圆点和文字之间的间距 */
        font-size: 15px;
    }
    .normal-class {
        color: #0A74F6; /* 正常考试显示蓝色 */
        font-size: 15px;
    }
    .abnormal-class::before {
        content: '切屏 ●';
        color: #FAC858;
        margin-right: 20px;
        font-size: 15px;
    }
    .abnormal-class {
        color: #FAC858;/* 切屏显示黄色 */
        font-size: 15px;
    }
    .substitution-class::before {
        content: '替考 ●';
        color: #F5222D;
        margin-right: 20px;
        font-size: 15px;
    }
    .substitution-class{
        color: #F5222D;/* 替考显示红色 */
        font-size: 15px;
    }
    .substitution1-class::before {
        content: '考试前人脸验证失败 ●';
        color: #8d8787;
        margin-right: 20px;
        font-size: 15px;
    }
    .substitution1-class{
        color: #8d8787;
        font-size: 15px;
    }
</style>